package com.webwork.lims.transport.controller;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.webwork.lims.common.controller.SuperCtrl;
import com.webwork.lims.common.dataobject.CtrlerAndTime;
import com.webwork.lims.orders.dataobject.Order;
import com.webwork.lims.orders.dataobject.OrderStatus;
import com.webwork.lims.orders.service.OrderService;
import com.webwork.lims.system.dataobject.Role;
import com.webwork.lims.system.dataobject.User;
import com.webwork.lims.transport.dataobject.Car;
import com.webwork.lims.transport.dataobject.CarStatus;
import com.webwork.lims.transport.dataobject.TransOrder;
import com.webwork.lims.transport.dataobject.TransStatus;
import com.webwork.lims.transport.dataobject.TransType;
import com.webwork.lims.transport.dataobject.Zone;
import com.webwork.lims.transport.service.CarsService;
import com.webwork.lims.transport.service.TransService;
import com.webwork.lims.transport.service.ZoneService;
import com.webwork.lims.util.Paging;
import com.webwork.lims.util.StrManager;

@Controller
@RequestMapping(value = "/transport")
public class TransController extends SuperCtrl {
	
	@Autowired
	private TransService transSve;
	
	@Autowired
	private OrderService orderSve;
	
	@Autowired
	private CarsService carSve;
	
	@Autowired
	private ZoneService zoneSve;

	@RequestMapping(value = "/trans")
	@Override
	public String mainPage() {
		return "trans";
	}
	
	@RequestMapping(value="loadStatus")
	@ResponseBody
	public ResponseEntity<String> loadStatus() {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		TransStatus[] status = TransStatus.useableValues();
		List<Object> ret = new ArrayList<Object>();
		for (TransStatus o : status) {
			Map<String, Object> map = new HashMap<String, Object>();
			map.put("value", o.getCode());
			map.put("name", o.getCode() + " - " + o.getMsg());
			ret.add(map);
		}
		return new ResponseEntity<String>(new Gson().toJson(ret).toString(), responseHeaders, HttpStatus.CREATED);
	}
	
	@RequestMapping(value = "queryTransList")
	@ResponseBody
	public ResponseEntity<String> queryList(
			@RequestParam(value = "page") int page,
			@RequestParam(value = "rows") int rows,
			@RequestParam(required = false, value = "cmd") String cmdStr,
			HttpServletRequest request)
					throws Exception {
		User user = (User) request.getSession(true).getAttribute("user");
		
		TransOrder queryObj = new TransOrder();
		if (!StrManager.isEmpty(cmdStr)) {
			queryObj = new Gson().fromJson(cmdStr, TransOrder.class);
			queryObj.setStatus(queryObj.getStatusCode());
		}
		if (user.getRole() == Role.DELIVERY) {
			Zone zoneQuery = new Zone();
			zoneQuery.setDelivery(user.getUserId());
			List<Zone> zones = zoneSve.query(zoneQuery);
			Zone thisZone = null;
			if (zones != null && zones.size() > 0) {
				thisZone = zones.get(0);
				queryObj.setPredict(thisZone.getZoneCode());
			}
		}
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		Map<String, Object> ret = new HashMap<String, Object>();
	
		ret.put("total", transSve.count(queryObj));
		ret.put("rows", transSve.query(queryObj, new Paging(page, rows)));
		
		return new ResponseEntity<String>(new Gson().toJson(ret).toString(), responseHeaders, HttpStatus.CREATED);
	}
	
	@RequestMapping(value = "getTrans")
	@ResponseBody
	public ResponseEntity<String> getTrans(@RequestParam("transId") String transId) {
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		TransOrder order = transSve.get(transId);
		order.setArrive(zoneSve.toChinese(order.getArrive()));
		return new ResponseEntity<String>(new Gson().toJson(order).toString(), responseHeaders, HttpStatus.CREATED);
	}
	
	@RequestMapping(value = "delivery")
	@ResponseBody
	public String delivery(@RequestParam("transId") String transId, HttpServletRequest request) {
		User user = (User) request.getSession(true).getAttribute("user");
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		TransOrder order = transSve.get(transId);
		if (order == null) {
			return FAIL;
		}
		order.setArrive("1");	//广州发货
		String[] zones = order.getWayLine().split("-");
		if (zones.length > 1) {
			Car queryObj = new Car();
			queryObj.setStatus(CarStatus.WAITING);
			queryObj.setZoneCode(Integer.valueOf(zones[0]));
			TransType type = TransType.NULL;
			Zone startZone = zoneSve.get(Integer.valueOf(zones[0]));
			Zone endZone = zoneSve.get(Integer.valueOf(zones[1]));
			if (!startZone.getCountry().equals(endZone.getCountry())) {
				type = TransType.AIRLINE;
			} else if (!startZone.getProvince().equals(endZone.getProvince())) {
				type = TransType.PROVINCIAL;
			} else if (!startZone.getCity().equals(endZone.getCity())){
				type = TransType.INTERCITY;
			}
			queryObj.setType(type);
			List<Car> cars = carSve.query(queryObj);
			if (cars != null && cars.size() > 0) {
				Car car = cars.get(0);
				order.setCarNum(car.getCarNum());
				car.setStatus(CarStatus.DELIVERY);
				carSve.update(car);
			} else {
				return "noCar";
			}
			order.setPredict(Integer.valueOf(zones[1]));
		} else {
			order.setPredict(1);
		}
		order.setStatus(TransStatus.DELIVERY);
		order.setDelivery(new CtrlerAndTime(user.getUserName(), new Date()));
		transSve.save(order);
		
		//更新运单状态
		List<Order> orders = orderSve.getByTransId(order.getTransId());
		for (Order o : orders) {
			o.setStatus(OrderStatus.DELIVERY);
			orderSve.save(o);
		}
		return SUCCESS;
	}
	
	@RequestMapping(value = "confirm")
	@ResponseBody
	public String confirm(@RequestParam("transId") String transId, HttpServletRequest request) {
		User user = (User) request.getSession(true).getAttribute("user");
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		TransOrder order = transSve.get(transId);
		if (order == null) {
			return FAIL;
		}
		Zone queryObj = new Zone();
		queryObj.setDelivery(user.getUserId());
		List<Zone> zones = zoneSve.query(queryObj);
		Zone thisZone = null;
		if (zones != null && zones.size() > 0) {
			thisZone = zones.get(0);
		} else {
			return FAIL;
		}
		if (order.getWayLine().indexOf("-") > -1) {
			order.setArrive(order.getArrive() + "-" + thisZone.getZoneCode());
		}
		order.setModify(new CtrlerAndTime(user.getUserName(), new Date()));
		if (!StrManager.isEmpty(order.getCarNum())) {
			Car car = carSve.get(order.getCarNum());
			car.setStatus(CarStatus.WAITING);
			carSve.save(car);
		}
		if (order.getWayLine().equals(order.getArrive())) {
			order.setStatus(TransStatus.COMPLETE);
			order.setComplete(new CtrlerAndTime(user.getUserName(), new Date()));
		} else {
			String[] strs = order.getWayLine().split("-");
			int j = 0;
			for (int i = 0; i < strs.length; i++) {
				if (thisZone.getZoneCode() == Integer.valueOf(strs[i])) {
					j = i;
					break;
				}
			}
			order.setPredict(Integer.valueOf(strs[j + 1]));
			Car carQuery = new Car();
			carQuery.setStatus(CarStatus.WAITING);
			carQuery.setZoneCode(thisZone.getZoneCode());
			TransType type = TransType.NULL;
			Zone startZone = zoneSve.get(thisZone.getZoneCode());
			Zone endZone = zoneSve.get(order.getPredict());
			if (!startZone.getCountry().equals(endZone.getCountry())) {
				type = TransType.AIRLINE;
			} else if (!startZone.getProvince().equals(endZone.getProvince())) {
				type = TransType.PROVINCIAL;
			} else if (!startZone.getCity().equals(endZone.getCity())){
				type = TransType.INTERCITY;
			}
			carQuery.setType(type);
			List<Car> cars = carSve.query(carQuery);
			if (cars != null && cars.size() > 0) {
				Car car2 = cars.get(0);
				order.setCarNum(car2.getCarNum());
				car2.setStatus(CarStatus.DELIVERY);
				carSve.update(car2);
			} else {
				return "noCar";
			}
		}
		
		transSve.save(order);
		
		//更新运单状态
		Order orderQuery = new Order();
		orderQuery.setTransId(order.getTransId());
		orderQuery.setZoneCode(thisZone.getZoneCode());
		List<Order> orders = orderSve.query(orderQuery);
		for (Order o : orders) {
			o.setStatus(OrderStatus.DISPATCH);
			orderSve.save(o);
		}
		
		return SUCCESS;
	}
	
	@RequestMapping(value = "cancelTrans")
	@ResponseBody
	public String cancelTrans(@RequestParam("transId") String transId, HttpServletRequest request) {
		User user = (User) request.getSession(true).getAttribute("user");
		HttpHeaders responseHeaders = new HttpHeaders();
		responseHeaders.add("Content-Type", "text/html; charset=utf-8");
		TransOrder order = transSve.get(transId);
		if (order == null) {
			return FAIL;
		}
		order.setStatus(TransStatus.CANCEL);
		order.setComplete(new CtrlerAndTime(user.getUserName(), new Date()));
		transSve.save(order);
		return SUCCESS;
	}
	
}
